package banmuoi.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import banmuoi.entity.Order;
import banmuoi.entity.OrderDetail;
import banmuoi.util.HibernateUtil;

@WebServlet("/crudOrder.do")
public class OrderAdmin extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//String value = checkLogin(req, resp);
		//if(value != null){
			//if(value.equals("1") || value.equals("3")){//admin hoặc ProductManager		
				
				//LẤY THAM SỐ TỪ CÁC REQUEST
				
				
				Session session = HibernateUtil.openSession();
			
				if (req.getParameter("duyet")!= null && req.getParameter("duyet") != "")
				{
					int orderId = Integer.parseInt(req.getParameter("orderid"));
					
					Transaction trans = session.beginTransaction();
					
					Order or = (Order) session.load(Order.class, orderId);
					
					or.setState(true);
					java.sql.Date ngay=new java.sql.Date(new java.util.Date().getTime());
					or.setRequireDate(ngay);
					
					session.update(or);
					trans.commit();
					resp.sendRedirect("crudOrder.do");
					return;
				}
				
				
				if (req.getParameter("btnSearch") != null)
				{
					if (req.getParameter("userid") !=null)
					{
						String hql = "FROM Order o where o.customer.id = " + req.getParameter("userid");
						Query query = session.createQuery(hql);
						
						List<Order> entities = query.list();
						req.setAttribute("entityOrder", entities);
					}
					
					if (req.getParameter("search") != null)
					{
						String hql = "FROM Order o where o.customer.name like :tenKhach";
						Query query = session.createQuery(hql);
						
						query.setString("tenKhach", "%" + req.getParameter("search") + "%");
						List<Order> entities = query.list();
						req.setAttribute("entityOrder", entities);
					}
				}
				else
				{
					//HIỆN DANH SÁCH
					String hql = "FROM Order";
					Query query = session.createQuery(hql);
					List<Order> entities = query.list();
					req.setAttribute("entityOrder", entities);
				}
				
	
				req.getRequestDispatcher("admin/OrderAdmin.jsp").forward(req, resp);			
				session.close();
			//}
		//}
		
		//else {
		//	req.getRequestDispatcher("admin/Login.jsp").forward(req, resp);
		//}
	}
}